package com.linchong.concurrency.chapter13;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.stream.IntStream;

/**
 * @Author:linchong
 * @CreateTime:2020-07-30 08:23
 * @Description:
 */
public class SimpleThreadPool {

	/**
	 * 线程池大小，默认值
	 */
	private final int size;


	private static volatile int seq = 0;

	private final static int DEFAULT_SIZE = 10;

	/**
	 * 线程公共前缀
	 */
	private final static String THREAD_PREFIX="SIMPLE_THREAD_POOL-";

	/**
	 * 线程池所在线程组
	 */
	private final static ThreadGroup GROUP = new ThreadGroup("POOL_GROUP");
	/**
	 * 定义任务队列
	 */
	private final static LinkedList<Runnable> TASK_QUEUE=new LinkedList<>();

	/**
	 * 自定义线程池
	 */
	private final static List<WorkerTask> THREAD_QUEUE = new ArrayList<>();

	public SimpleThreadPool(int size) {
		this.size = size;
	}

	public SimpleThreadPool(){
		this(DEFAULT_SIZE);
		//初始化线程池
		init();
	}

	private void init(){
		for (int i = 0; i < size; i++) {
			createWorkTask();
		}
	}


	/**
	 * 提交任务
	 * @param runnable
	 */
	public void submit(Runnable runnable){
		synchronized (TASK_QUEUE){
			TASK_QUEUE.addLast(runnable);
			TASK_QUEUE.notifyAll();
		}
	}

	/**
	 * 创建线程池
	 */
	private void createWorkTask(){
		WorkerTask task = new WorkerTask(GROUP,THREAD_PREFIX+(seq++));
		task.start();
		THREAD_QUEUE.add(task);
	}

	/**
	 * 定义线程池状态
	 */
	private enum TaskState{
		/**
		 * 空闲
		 */
		FREE,
		/**
		 * 运行
		 */
		RUNNING,
		/**
		 * 阻塞
		 */
		BLOCKED,
		/**
		 * 死亡
		 */
		DEAD
	}

	private static class WorkerTask extends Thread{
        private volatile TaskState taskState = TaskState.FREE;

        public TaskState getTaskState(){
        	return this.taskState;
        }

        public WorkerTask(ThreadGroup group,String name){
        	super(group,name);
        }

		@Override
		public void run() {
        	OUTER:
			while(this.taskState!=TaskState.DEAD){
				Runnable runnable;
				synchronized (TASK_QUEUE){
					while (TASK_QUEUE.isEmpty()){
						try {
							taskState = TaskState.BLOCKED;
							TASK_QUEUE.wait();
						} catch (InterruptedException e) {
							//退出时，跳出位置，继续执行
							break OUTER;
						}
					}
					//任务队列有值，继续执行
					runnable = TASK_QUEUE.removeFirst();
					if(null!=runnable){
						taskState = TaskState.RUNNING;
						runnable.run();
						taskState = TaskState.FREE;
					}
				}
			}
		}

		public void close(){
        	this.taskState = TaskState.DEAD;
        }

	}

	public static void main(String[] args) {
		SimpleThreadPool threadPool = new SimpleThreadPool();

		for (int i = 0; i < 40; i++) {
			threadPool.submit(()->{
				System.out.println("the runnable  be serviced by "+Thread.currentThread()+" start.");
				try {
					Thread.sleep(1_000);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
				System.out.println("the runnable  be serviced by "+Thread.currentThread()+" finished.");
			});
			System.out.println("====提交了====");
		}

	}


}
